package cn.hqc.org.service.impl;


import cn.hqc.basic.jwt.UserInfo;
import cn.hqc.basic.query.BaseQuery;
import cn.hqc.basic.service.impl.BaseServiceImpl;
import cn.hqc.basic.utils.MD5Utils;
import cn.hqc.basic.utils.PageList;
import cn.hqc.basic.utils.StrUtils;
import cn.hqc.basic.utils.ThreadLocalUtil;
import cn.hqc.org.domain.Employee;
import cn.hqc.org.domain.Shop;
import cn.hqc.org.service.EmployeeService;
import cn.hqc.org.vo.EmpAndRoleVo;
import cn.hqc.system.mapper.RoleMapper;
import cn.hqc.user.domain.Logininfo;
import cn.hqc.user.mapper.LogininfoMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class EmployeeServiceImpl extends BaseServiceImpl<Employee> implements EmployeeService {

    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private RoleMapper roleMapper;

    @Override
    @Transactional
    public void add(Employee employee) {
        String salt = StrUtils.getComplexRandomString(32);
        String password = MD5Utils.encrypByMd5(salt + "1");
        employee.setSalt(salt);
        employee.setPassword(password);
        // 添加logininfo
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(employee, logininfo);
        logininfo.setDisable(true);
        logininfo.setType(0);
        logininfoMapper.add(logininfo);
        // 添加 员工
        // 如果你当前人有店铺 那么就给employee对象加上 没有就算了
        UserInfo userInfo = ThreadLocalUtil.get();
        if (null != userInfo.getShop()) {
            employee.setShopId(userInfo.getShop().getId());
        }
        employee.setLogininfoId(logininfo.getId());
        super.add(employee);

        // 添加员工的时候 同步选择角色 那么我们就需要添加员工和角色的中间表
        if (!CollectionUtils.isEmpty(employee.getRoles())) {
            roleMapper.addMiddle(employee.getId(), employee.getRoles());
        }
    }

    @Override
    @Transactional
    public void update(Employee employee) {
        // 添加logininfo
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(employee, logininfo);
        logininfoMapper.update(logininfo);
        // 添加 员工
        super.update(employee);
        // 先删除 再添加
        roleMapper.deleteMiddle(employee.getId());
        // 添加员工的时候 同步选择角色 那么我们就需要添加员工和角色的中间表
        roleMapper.addMiddle(employee.getId(), employee.getRoles());
    }

    @Override
    public List<Employee> findByDeptId(Long deptId) {
        List<Employee> allEmps = this.findAll();
        return allEmps.stream().filter(emp -> deptId.equals(emp.getDepartmentId()))
                .collect(Collectors.toList());
    }

    @Override
    public List<Employee> findByShopId() {
        // 先获取到当前登录人的shopId
        UserInfo userInfo = ThreadLocalUtil.get();
        Shop shop = userInfo.getShop();
        if (null == shop) {
            return this.findAll();
        }
        return this.findAll().stream().filter(emp -> Objects.nonNull(emp.getShopId()) &&
                        emp.getShopId().equals(shop.getId()))
                .collect(Collectors.toList());
    }


    @Override
    public PageList<Employee> queryByPage(BaseQuery query) {
        PageList<Employee> pageList = super.queryByPage(query);
        // 在当前的这个pageList中 将属于他们的roles集合加进去
        List<Employee> emps = pageList.getRows();
        // 获取到emps所有的 id集合
        List<Long> empIds = emps.stream().map(Employee::getId).collect(Collectors.toList());
        // 根据empIds 查询对应的所有的 roleIds 只需要查询中间表即可
        List<EmpAndRoleVo> resultTmp = roleMapper.findByEmpIds(empIds);
        // 将集合根据 empid进行分组 转成map key:empId    value：List<Long> roles
        Map<Long, List<Long>> roleMap = resultTmp.stream().collect(Collectors.groupingBy(EmpAndRoleVo::getEmployeeId
                , Collectors.mapping(EmpAndRoleVo::getRoleId, Collectors.toList())));
        emps.forEach(emp -> {
            List<Long> roleIds = roleMap.get(emp.getId());
            emp.setRoles(roleIds);
        });

        return pageList;
    }
}
